﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace RepeatingWordsCount
{
    class RepeatingWordsCount
    {
        static void Main()
        {
            try
            {
                string line;
                List<string> words = new List<string>();

                //Read words
                using (StreamReader reader = new StreamReader("..\\..\\words.txt"))
                {
                    while ((line = reader.ReadLine()) != null)
                    {
                        words.Add(line);
                    }
                }
                int[] values = new int[words.Count];

                // Count words
                using (StreamReader reader = new StreamReader("..\\..\\test.txt"))
                {
                    while ((line = reader.ReadLine()) != null)
                    {
                        for (int wordIndex = 0, length = values.Length; wordIndex < length; wordIndex++)
                        {
                            values[wordIndex] += Regex.Matches(line, @"\b" + words[wordIndex] + @"\b").Count;
                        }
                    }
                }

                // Write output
                using (StreamWriter writer = new StreamWriter("..\\..\\result.txt"))
                {
                    for (int wordIndex = 0, length = values.Length; wordIndex < length; wordIndex++)
                    {
                        writer.WriteLine("{0} - {1}", words[wordIndex], values[wordIndex]);
                    }
                }
            }
            catch (FileNotFoundException excFileNotFound)
            {
                Console.WriteLine(excFileNotFound.Message);
            }
            catch (ArgumentNullException excArgumentNull)
            {
                Console.WriteLine(excArgumentNull.Message);
            }
            catch (DirectoryNotFoundException excDirNotFound)
            {
                Console.WriteLine(excDirNotFound);
            }
            catch (IOException excIO)
            {
                Console.WriteLine(excIO);
            }
            catch (UnauthorizedAccessException excAccess)
            {
                Console.WriteLine(excAccess);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
        }
    }
}
